#!/usr/bin/env python
#
# Copyright (C) 2005-2020 ABINIT Group (Yann Pouillon)
#
# This file is part of the ABINIT software package. For license information,
# please see the COPYING file in the top-level directory of the ABINIT source
# distribution.
#
from __future__ import print_function, division, absolute_import #, unicode_literals

try:
    from ConfigParser import ConfigParser
except ImportError:
    from configparser import ConfigParser
from time import gmtime,strftime

try:
    from commands import getoutput
except:
    from subprocess import getoutput
import os
import re
import sys

class MyConfigParser(ConfigParser):

  def optionxform(self,option):
    return str(option)

# ---------------------------------------------------------------------------- #

#
# Subroutines
#

# Script template
def symlink_maker(name,stamp):

  return """#!/bin/sh

# Generated by %s on %s

#
# Symlink maker for compatibility with the legacy build workflow
#

#
# IMPORTANT NOTE
#
# This file has been automatically generated by the %s
# script. If you try to edit it, your changes will systematically be
# overwritten.
#

# Init
LN_S="@LN_S@"

cd src
""" % (name,stamp,name)



# ---------------------------------------------------------------------------- #

#
# Main program
#

# Initial setup
my_name    = "make-symlink-maker-in"
my_configs = {"libs":"config/specs/corelibs.conf"}
my_output  = "config/split/make-src-symlinks.in"

# Check if we are in the top of the ABINIT source tree
if ( not os.path.exists("configure.ac") or
     not os.path.exists("src/98_main/abinit.F90") ):
  print("%s: You must be in the top of an ABINIT source tree." % my_name)
  print("%s: Aborting now." % my_name)
  sys.exit(1)

# Read config file(s)
for cnf_file in my_configs.values():
  if ( os.path.exists(cnf_file) ):
    if ( re.search("\.cf$",cnf_file) ):
      exec(compile(open(cnf_file).read(), cnf_file, 'exec'))
  else:
    print("%s: Could not find config file (%s)." % (my_name,cnf_file))
    print("%s: Aborting now." % my_name)
    sys.exit(2)

# What time is it?
now = strftime("%Y/%m/%d %H:%M:%S +0000",gmtime())

# Create destination directory
try:
  os.makedirs("config/split", exist_ok=True)
except TypeError:
  try:
    os.makedirs("config/split")
  except OSError:
    pass

# Init
cnf = MyConfigParser()
cnf.read(my_configs["libs"])
abinit_corelibs = cnf.sections()
abinit_corelibs.sort()

# Create script
links = symlink_maker(my_name, now)
for lib in abinit_corelibs:
  if ( cnf.get(lib, "parent") == "common" ):
    par_dir = "../shared/common/src/%s" % lib
  elif ( cnf.get(lib, "parent") == "libpaw" ):
    par_dir = "../shared/libpaw/src"
  else:
    par_dir = ""
  if ( cnf.get(lib, "parent") != "core" ):
    links += "test -e %s || ${LN_S} %s %s\n" % (lib, par_dir, lib)

# Write down script
with open(my_output, "w") as script_file:
  script_file.write(links)
